<?php

/**
 * Created by PhpStorm.
 * User: TC
 * Date: 2016/3/24
 * Time: 15:49
 * 简报控制器
 */
require_once dirname(__FILE__) . '/../model/BriefModel.php';
require_once dirname(__FILE__) . '/../db/medoo.php';

class BriefController
{
  /*
   * 增加简报
   */
  public static function AddBrief($type, $img, $title, $content, $author)
  {
    if (!$type) return false;
    if (!$img) return false;
    if (!$title) return false;
    if (!$content) return false;
    if (!$author) return false;
    $database = new medoo();
    $lastId = $database->insert(BriefModel::TABLE_NAME, [
      BriefModel::TYPE_FIELD => $type,
      BriefModel::IMG_IFELD => $img,
      BriefModel::TITLE_FIELD => $title,
      BriefModel::CONTENT_FIELD => $content,
      BriefModel::AUTHOR_FIELD => $author,
      BriefModel::CREATEAT_FIELD => date('Y-m-d H:i:s'),
      BriefModel::WEIGHT_FIELD => 0
    ]);
    return $lastId > 0 ? $lastId : false;
  }

  /*
   * 删除简报
   */
  public static function Remove($id)
  {
    if (!$id) return false;
    $database = new medoo();
    $row = $database->delete(BriefModel::TABLE_NAME, [BriefModel::ID_FIELD => $id]);
    return $row == 1 ? true : false;
  }

  /*
   * 获取简报列表
   */
  public static function BriefListByWeight($page = 1, $count = 20)
  {
    if ($page < 1) return false;
    $database = new medoo();
    $index = ($page - 1) * $count;
    $briefList = $database->select(BriefModel::TABLE_NAME, '*', [
      'ORDER' => BriefModel::WEIGHT_FIELD . ' DESC',
      'LIMIT' => [$index, $count]
    ]);
    return $briefList;
  }

  /*
 * 获取简报列表
 */
  public static function BriefListByTime($page = 1, $count = 20, $orderType = 1)
  {
    if ($page < 1) return false;
    $database = new medoo();
    $order = $orderType == 1 ? ' DESC' : ' ASC';
    $index = ($page - 1) * $count;
    $briefList = $database->select(BriefModel::TABLE_NAME, '*', [
      'ORDER' => BriefModel::CREATEAT_FIELD . $order,
      'LIMIT' => [$index, $count]
    ]);
    return $briefList;
  }

  /*
   * 修改排序权重值
   */
  public static function ModifyWeight($id, $weight)
  {
    if(!$id) return false;
    if(!$weight) return false;
    $database = new medoo();
    $database->update(BriefModel::TABLE_NAME,[BriefModel::WEIGHT_FIELD=>$weight],[BriefModel::ID_FIELD=>$id]);
    return true;
  }

  /*
   * 获取指定id的简报
   */
  public static function FindBriefById($id){
    if(!$id) return false;
    $database = new medoo();
    $briefArr = $database->select(BriefModel::TABLE_NAME,'*',[BriefModel::ID_FIELD=>$id]);
    if(count($briefArr)>0){
      return $briefArr[0];
    } else {
      return false;
    }
  }
}